import uniToken from './uni-token'
import {
  userCollection,
  log
} from '../share/index'
import loginCheck from '../common/login-check'
import getAlipayApi from '../common/alipay-api'
import registerExec from '../common/register-exec'

async function loginByAlipay (code) {
  let params = code
  if (typeof code === 'string') {
    params = {
      code
    }
  }
  const clientPlatform = params.platform || __ctx__.PLATFORM
  const {
    openid
  } = await getAlipayApi({
    platform: clientPlatform
  }).code2Session(params.code)
  if (!openid) {
    return {
      code: 10501,
      msg: '获取openid失败'
    }
  }
  const userList = await userCollection.where({
    ali_openid: openid
  }).get()
  // openid已注册
  if (userList && userList.data && userList.data.length > 0) {
    const userMatched = userList.data[0]

    try {
      const loginCheckRes = await loginCheck(userMatched)
      if (loginCheckRes.code !== 0) {
        return loginCheckRes
      }
      const userInfo = loginCheckRes.user
      const tokenList = userInfo.token

      log('开始修改最后登录时间，写入openid')
      const {
        token,
        tokenExpired
      } = uniToken.createToken(userMatched)
      log('token', token)
      tokenList.push(token)
      const upRes = await userCollection.doc(userMatched._id).update({
        last_login_date: new Date().getTime(),
        last_login_ip: __ctx__.CLIENTIP,
        token: tokenList
      })
      log('upRes', upRes)
      return {
        code: 0,
        msg: '登录成功',
        token,
        uid: userMatched._id,
        username: userMatched.username,
        openid,
        type: 'login',
        userInfo: userMatched,
        tokenExpired,
        mobileConfirmed: userInfo.mobile_confirmed === 1,
        emailConfirmed: userInfo.email_confirmed === 1
      }
    } catch (e) {
      log('写入异常：', e)
      return {
        code: 90001,
        msg: '数据库写入异常'
      }
    }
  } else {
    try {
      const user = {
        register_date: new Date().getTime(),
        register_ip: __ctx__.CLIENTIP,
        ali_openid: openid
      }
      const myInviteCode = params.myInviteCode
      if (myInviteCode) {
        user.my_invite_code = myInviteCode
      }
      const registerResult = await registerExec(user)
      if (registerResult.code > 0) {
        return registerResult
      }
      const addRes = registerResult.result
      const uid = addRes.id
      const {
        token,
        tokenExpired
      } = uniToken.createToken({
        _id: uid
      })
      await userCollection.doc(uid).update({
        token: [token]
      })
      return {
        code: 0,
        msg: '登录成功',
        token: token,
        uid: addRes.id,
        openid,
        type: 'register',
        tokenExpired,
        mobileConfirmed: false,
        emailConfirmed: false
      }
    } catch (e) {
      log('写入异常：', e)
      return {
        code: 90001,
        msg: '数据库写入异常'
      }
    }
  }
}

export default loginByAlipay
